package com.innovation.ic.b1b.monitor.base.service.masterSlave.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.innovation.ic.b1b.monitor.base.handler.ElasticsearchAvailableJobHandler;
import com.innovation.ic.b1b.monitor.base.mapper.ElasticsearchAvailableJobMapper;
import com.innovation.ic.b1b.monitor.base.model.Elasticsearch;
import com.innovation.ic.b1b.monitor.base.model.ElasticsearchAvailableJob;
import com.innovation.ic.b1b.monitor.base.pojo.constant.ElasticsearchAvailableJobConstant;
import com.innovation.ic.b1b.monitor.base.pojo.constant.JobDataMapConstant;
import com.innovation.ic.b1b.monitor.base.pojo.constant.TableNameConstant;
import com.innovation.ic.b1b.monitor.base.pojo.enums.EnableEnum;
import com.innovation.ic.b1b.monitor.base.pojo.variable.ServiceResult;
import com.innovation.ic.b1b.monitor.base.pojo.variable.elasticsearchAvailableJob.ElasticsearchAvailableJobInfoRespPojo;
import com.innovation.ic.b1b.monitor.base.pojo.variable.elasticsearchAvailableJob.ElasticsearchAvailableJobListRespData;
import com.innovation.ic.b1b.monitor.base.service.masterSlave.ElasticsearchAvailableJobService;
import com.innovation.ic.b1b.monitor.base.service.masterSlave.ServiceHelper;
import com.innovation.ic.b1b.monitor.base.vo.elasticsearchAvailableJob.ElasticsearchAvailableJobAddVo;
import com.innovation.ic.b1b.monitor.base.vo.elasticsearchAvailableJob.ElasticsearchAvailableJobListQueryVo;
import com.innovation.ic.b1b.monitor.base.vo.elasticsearchAvailableJob.ElasticsearchAvailableJobUpdateVo;
import org.quartz.JobDataMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class ElasticsearchAvailableJobServiceImpl extends ServiceImpl<ElasticsearchAvailableJobMapper, ElasticsearchAvailableJob> implements ElasticsearchAvailableJobService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private ServiceHelper serviceHelper;

    /**
     * 添加elasticsearch监控任务
     * @param elasticsearchAvailableJobAddVo 添加Elasticsearch可用任务的Vo类
     * @return 返回添加结果
     */
    @Override
    public ServiceResult<Boolean> add(ElasticsearchAvailableJobAddVo elasticsearchAvailableJobAddVo) {
        boolean result = Boolean.FALSE;
        String message;

        Boolean aBoolean = judgeIfHaveSameData(null, elasticsearchAvailableJobAddVo.getElasticsearchId());
        if (aBoolean) {
            message = "当前elasticsearch监控任务已存在，请勿重复添加";
        } else {
            // 校验elasticsearchId是否存在
            Elasticsearch elasticsearch = serviceHelper.getElasticsearchMapper().selectById(elasticsearchAvailableJobAddVo.getElasticsearchId());
            if (elasticsearch != null) {
                ElasticsearchAvailableJob elasticsearchAvailableJob = new ElasticsearchAvailableJob();
                BeanUtils.copyProperties(elasticsearchAvailableJobAddVo, elasticsearchAvailableJob);
                if (elasticsearchAvailableJob.getEnable() == null) {
                    elasticsearchAvailableJob.setEnable(EnableEnum.NO.getCode());
                }
                elasticsearchAvailableJob.setCreateTime(new Date(System.currentTimeMillis()));
                int insert = serviceHelper.getElasticsearchAvailableJobMapper().insert(elasticsearchAvailableJob);
                if (insert > 0) {
                    message = ServiceResult.INSERT_SUCCESS;
                    result = Boolean.TRUE;

                    String jobId = TableNameConstant.ELASTICSEARCH_AVAILABLE_JOB + "_" + elasticsearchAvailableJob.getId();

                    // 组装任务参数
                    JobDataMap jobDataMap = new JobDataMap();
                    jobDataMap.put(JobDataMapConstant.ID, elasticsearchAvailableJob.getId());

                    serviceHelper.getQuartzManager().createScheduleJob(jobId, ElasticsearchAvailableJobHandler.class.getName(), "ElasticsearchAvailableJobHandler", jobDataMap, elasticsearchAvailableJob.getScheduleExpression());
                } else {
                    message = ServiceResult.INSERT_FAIL;
                }
            } else {
                message = "elasticsearch信息不存在，请配置elasticsearch信息后重新添加elasticsearch监控任务";
            }
        }

        ServiceResult<Boolean> serviceResult = new ServiceResult<>();
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(result);
        serviceResult.setMessage(message);
        return serviceResult;
    }

    /**
     * 查询elasticsearch监控任务列表
     * @param elasticsearchAvailableJobListQueryVo 查询Elasticsearch监控任务列表的Vo类
     * @param isMain 是否查询主库
     * @return 返回查询结果
     */
    @Override
    public ServiceResult<PageInfo<ElasticsearchAvailableJobListRespData>> queryList(ElasticsearchAvailableJobListQueryVo elasticsearchAvailableJobListQueryVo, Boolean isMain) {
        PageHelper.startPage(elasticsearchAvailableJobListQueryVo.getPageNo(), elasticsearchAvailableJobListQueryVo.getPageSize());

        // 查询elasticsearch监控任务列表数据
        List<ElasticsearchAvailableJobListRespData> data = serviceHelper.getElasticsearchAvailableJobMapper().queryList(elasticsearchAvailableJobListQueryVo);
        PageInfo<ElasticsearchAvailableJobListRespData> pageInfo = new PageInfo<>(data);

        return ServiceResult.ok(pageInfo, ServiceResult.SELECT_SUCCESS);
    }

    /**
     * 删除elasticsearch监控任务
     *
     * @param id 主键id
     * @return 返回删除结果
     */
    @Override
    public ServiceResult<Boolean> delete(Integer id) {
        boolean result = Boolean.FALSE;
        String message = ServiceResult.DELETE_FAIL;

        int i = serviceHelper.getElasticsearchAvailableJobMapper().deleteById(id);
        if (i > 0) {
            logger.info("已删除id为[{}]mysql监控任务", id);
            result = Boolean.TRUE;
            message = ServiceResult.DELETE_SUCCESS;

            try {
                // 删除任务
                String jobId = TableNameConstant.ELASTICSEARCH_AVAILABLE_JOB + "_" + id;
                serviceHelper.getQuartzManager().deleteScheduleJob(jobId);
            }catch (Exception e){
                logger.info("删除elasticsearch监控后台任务失败,原因:", e);
            }
        } else {
            logger.info("删除id为[{}]mysql监控任务失败，数据不存在", id);
        }

        return ServiceResult.ok(result, message);
    }

    /**
     * 获取elasticsearch监控任务详情
     * @param id 主键id
     * @param isMain 是否查询主库
     * @return 返回查询结果
     */
    @Override
    public ServiceResult<ElasticsearchAvailableJobInfoRespPojo> info(Integer id, Boolean isMain) {
        ElasticsearchAvailableJobInfoRespPojo result = serviceHelper.getElasticsearchAvailableJobMapper().info(id);
        return ServiceResult.ok(result, ServiceResult.SELECT_SUCCESS);
    }

    /**
     * 更新elasticsearch监控任务
     *
     * @param elasticsearchAvailableJobUpdateVo 更新Elasticsearch可用任务的Vo类
     * @return 返回更新结果
     */
    @Override
    public ServiceResult<Boolean> update(ElasticsearchAvailableJobUpdateVo elasticsearchAvailableJobUpdateVo) {
        Boolean aBoolean = judgeIfHaveSameData(elasticsearchAvailableJobUpdateVo.getId(), elasticsearchAvailableJobUpdateVo.getElasticsearchId());
        if (aBoolean) {
            ServiceResult<Boolean> serviceResult = new ServiceResult<>();
            serviceResult.setSuccess(Boolean.TRUE);
            serviceResult.setResult(Boolean.FALSE);
            serviceResult.setMessage("当前elasticsearch监控任务已存在，请勿重复添加");
            return serviceResult;
        } else {
            // 校验elasticsearchId是否存在
            Elasticsearch elasticsearch = serviceHelper.getElasticsearchMapper().selectById(elasticsearchAvailableJobUpdateVo.getElasticsearchId());
            if (elasticsearch != null) {
                ElasticsearchAvailableJob historyData = serviceHelper.getElasticsearchAvailableJobMapper().selectById(elasticsearchAvailableJobUpdateVo.getId());

                int i = serviceHelper.getElasticsearchAvailableJobMapper().updateInfo(elasticsearchAvailableJobUpdateVo);
                if (i > 0) {
                    logger.info("更新id为[{}]elasticsearch监控任务成功", elasticsearchAvailableJobUpdateVo.getId());

                    Integer enable = elasticsearchAvailableJobUpdateVo.getEnable();
                    // 原来是启用现在关闭时需要暂停后台任务
                    if(historyData.getEnable().intValue() == EnableEnum.YES.getCode().intValue() && enable.intValue() == EnableEnum.NO.getCode().intValue()){
                        String jobId = TableNameConstant.ELASTICSEARCH_AVAILABLE_JOB + "_" + elasticsearchAvailableJobUpdateVo.getId();
                        logger.info("暂停后台任务,jobId:[{}]", jobId);
                        serviceHelper.getQuartzManager().pauseScheduleJob(jobId);
                    }else if(historyData.getEnable().intValue() == EnableEnum.NO.getCode().intValue() && enable.intValue() == EnableEnum.YES.getCode().intValue()) {
                        // 原来是关闭现在启用任务时需要恢复后台任务
                        String jobId = TableNameConstant.ELASTICSEARCH_AVAILABLE_JOB + "_" + elasticsearchAvailableJobUpdateVo.getId();
                        logger.info("恢复后台任务,jobId:[{}]", jobId);
                        serviceHelper.getQuartzManager().resumeScheduleJob(jobId);
                    }else{
                        String scheduleExpression = elasticsearchAvailableJobUpdateVo.getScheduleExpression();
                        if(elasticsearchAvailableJobUpdateVo.getEnable().intValue() == EnableEnum.YES.getCode().intValue() && !historyData.getScheduleExpression().equals(scheduleExpression)){
                            String jobId = TableNameConstant.ELASTICSEARCH_AVAILABLE_JOB + "_" + elasticsearchAvailableJobUpdateVo.getId();
                            serviceHelper.getQuartzManager().updateScheduleJob(jobId, scheduleExpression);
                        }
                    }

                    return ServiceResult.ok(Boolean.TRUE, ServiceResult.UPDATE_SUCCESS);
                } else {
                    logger.info("更新id为[{}]elasticsearch监控任务失败", elasticsearchAvailableJobUpdateVo.getId());
                    return ServiceResult.ok(Boolean.FALSE, ServiceResult.UPDATE_FAIL);
                }
            } else {
                logger.info("elasticsearchId=[{}]的信息不存在", elasticsearchAvailableJobUpdateVo.getElasticsearchId());
                return ServiceResult.error(ServiceResult.UPDATE_FAIL);
            }
        }
    }

    /**
     * 执行任务
     *
     * @param id 主键id
     * @return 返回执行结果
     */
    @Override
    public ServiceResult<Boolean> executeJob(Integer id) {
        ServiceResult<Boolean> serviceResult = new ServiceResult<>();

        try {
            String jobId = TableNameConstant.ELASTICSEARCH_AVAILABLE_JOB + "_" + id;
            serviceHelper.getQuartzManager().runOnce(jobId);
        } catch (Exception e) {
            serviceResult.setMessage(ServiceResult.OPERATE_FAIL);
            serviceResult.setResult(Boolean.FALSE);
            serviceResult.setSuccess(Boolean.FALSE);
            return serviceResult;
        }

        serviceResult.setMessage(ServiceResult.OPERATE_SUCCESS);
        serviceResult.setResult(Boolean.TRUE);
        serviceResult.setSuccess(Boolean.TRUE);
        return serviceResult;
    }

    @Override
    public List<ElasticsearchAvailableJob> findByElasticsearchId(Integer elasticsearchId) {
        QueryWrapper<ElasticsearchAvailableJob> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("elasticsearch_id", elasticsearchId);
        return this.baseMapper.selectList(queryWrapper);
    }

    /**
     * 判断是否有相同数据
     *
     * @param id              主键id
     * @param elasticsearchId elasticsearch id
     * @return 返回判断结果
     */
    private Boolean judgeIfHaveSameData(Integer id, Integer elasticsearchId) {
        Boolean result = Boolean.FALSE;

        QueryWrapper<ElasticsearchAvailableJob> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ElasticsearchAvailableJobConstant.ELASTICSEARCH_ID, elasticsearchId);
        if (id != null) {
            queryWrapper.ne(ElasticsearchAvailableJobConstant.ID, id);
        }
        Integer selectCount = serviceHelper.getElasticsearchAvailableJobMapper().selectCount(queryWrapper);
        if (selectCount > 0) {
            result = Boolean.TRUE;
        }

        return result;
    }
}